package com.ayou.eggguard.farm.service.impl;

import com.ayou.common.utils.PageBean;
import com.ayou.eggguard.farm.mapper.CaseMapper;
import com.ayou.eggguard.farm.mapper.CautionMapper;
import com.ayou.eggguard.farm.mapper.TreatmentMapper;
import com.ayou.eggguard.farm.pojo.Case;
import com.ayou.eggguard.farm.pojo.Treatment;
import com.ayou.eggguard.farm.service.TreatmentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class TreatmentServiceImpl implements TreatmentService {

    @Autowired
    private TreatmentMapper treatmentMapper;

    @Autowired
    private CaseMapper caseMapper;

    @Autowired
    private CautionMapper cautionMapper;
    @Override
    public PageBean<Treatment> getTreatmentList(Integer pageNum, Integer pageSize, String coopNumber) {
        PageBean<Treatment> pb=new PageBean<>();
        PageHelper.startPage(pageNum,pageSize);
        List<Treatment> list=treatmentMapper.getTreatmentList(coopNumber);
        Page<Treatment> p= (Page<Treatment>) list;
        pb.setItems(p.getResult());
        pb.setTotal(p.getTotal());
        return pb;
    }

    @Override
    public void delete(Integer id) {
        treatmentMapper.delete(id);
    }

    @Override
    public void add(Integer cautionId, Treatment treatment) {
        if(cautionId!=null){
            cautionMapper.updateCautionStatus(cautionId);
        }
        //获取病历数据
        Case newCase=new Case();
        newCase.setCoopNumber(treatment.getCoopNumber());
        newCase.setColumnNumber(treatment.getColumnNumber());
        newCase.setStoreyNumber(treatment.getStoreyNumber());
        newCase.setCageNumber(treatment.getCageNumber());
        newCase.setAction(treatment.getAction());
        newCase.setFeature(treatment.getFeature());
        newCase.setCheckResult(treatment.getCheckResult());
        newCase.setDiagnoseResult(treatment.getDiagnoseResult());
        newCase.setCheatMethod(treatment.getTreatMethod());
        newCase.setCheatResult(treatment.getTreatResult());

        //生成病历编号
        LocalDateTime time=treatment.getTreatTime();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String formattedDateTime = time.format(formatter);
        String caseNumber=treatment.getCoopNumber()+formattedDateTime+treatment.getColumnNumber()+treatment.getStoreyNumber()+treatment.getCageNumber();
        newCase.setCaseNumber(caseNumber);

        //添加诊断记录的同时添加病历
        caseMapper.add(newCase);
        treatmentMapper.add(treatment);
    }

    @Override
    public void update(Treatment treatment) {
        treatmentMapper.update(treatment);
    }
}
